package org.jflame.context.spring.converter;

import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;

/**
 * 时间戳与时间类型转换器.支持java.util.Date及子类(如:java.sql.Date,java.sql.Time,java.sql.Timestamp)转换.
 * 
 * @author charles.zhang
 */
public class TimestampStrToDateFormatter<T extends Date> implements Formatter<T> {

    private final Class<T> dateClass;

    /**
     * 构造函数
     * 
     * @param targetClass 具体时间类型
     */
    @SuppressWarnings("unchecked")
    public TimestampStrToDateFormatter(Class<T> targetClass) {
        this.dateClass = targetClass == null ? (Class<T>) Date.class : targetClass;
    }

    @Override
    public String print(T source, Locale locale) {
        return String.valueOf(source.getTime());
    }

    @Override
    public T parse(String text, Locale locale) throws ParseException {
        Date val = null;
        try {
            val = new Date(Long.parseLong(text.trim()));
        } catch (NumberFormatException e) {
            throw new ParseException(e.getMessage(), 0);
        }
        return convertTargetType(val);
    }

    @SuppressWarnings({ "unchecked" })
    private T convertTargetType(Date val) {
        if (dateClass == java.util.Date.class) {
            return (T) val;
        } else if (dateClass == java.sql.Date.class) {
            return (T) new java.sql.Date(val.getTime());
        } else if (dateClass == java.sql.Time.class) {
            return (T) new java.sql.Time(val.getTime());
        } else if (dateClass == java.sql.Timestamp.class) {
            return (T) new java.sql.Timestamp(val.getTime());
        } else {
            throw new IllegalStateException("unsupported " + dateClass.getName());// 只有3个子类,不应该走到这
        }
    }

    public void register(FormatterRegistry registry) {
        registry.addFormatterForFieldType(dateClass, this);
    }

}
